package com.ooqiu.gaming.components.retrofit.progress;

import android.content.Context;
import android.widget.Toast;

import io.reactivex.observers.DefaultObserver;


public abstract class ProgressSubscriber<T> extends DefaultObserver<T> implements ProgressCancelListener {

    private static final String TAG = "ProgressSubscriber";
    private ProgressDialogHandler mProgressDialogHandler;
    private Context context;

    public ProgressSubscriber(Context context) {
        this.context = context;
        mProgressDialogHandler = new ProgressDialogHandler(context, this, true);

    }


    private void showProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mProgressDialogHandler = null;
        }
    }

    @Override
    public void onStart() {
        showProgressDialog();
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
        onFinish();
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        dismissProgressDialog();
        handleError(e);
        onFinish();
    }

    @Override
    public abstract void onNext(T t);

    public abstract void onFinish();

    @Override
    public void onCancelProgress() {
        cancel();
        onFinish();
    }

    public void handleError(Throwable e) {
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
    }


}
